package com.gxuwz.stats.config;

import com.gxuwz.stats.security.jwt.JwtRequestFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletResponse;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService jwtUserDetailsService;

    @Autowired
    private JwtRequestFilter jwtRequestFilter;

    // 使用 @Lazy 注解避免循环依赖
    @Autowired
    @Lazy
    private PasswordEncoder passwordEncoder;

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(jwtUserDetailsService).passwordEncoder(passwordEncoder);
    }

    @Bean
    @Lazy // 延迟加载，避免循环依赖
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests()
                .antMatchers("/auth/**").permitAll()
//                .antMatchers("/user/**").hasRole("管理员")
                .antMatchers("/user/current").authenticated()
                .antMatchers("/user/importData").permitAll()
                .antMatchers("/totalWork/importTotalWork").permitAll()
                .antMatchers("/researchProject/importData").permitAll()
                .antMatchers("/academicWork/import").permitAll()
                .antMatchers("/sumImportData/excel").permitAll()
                .anyRequest().authenticated()
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
    }


////    @Override
////    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
////        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
////    }
//
//
////    @Bean
////    @Override
////    public AuthenticationManager authenticationManagerBean() throws Exception {
////        return super.authenticationManagerBean();
////    }
//
//    @Override
//    protected void configure(HttpSecurity http) throws Exception {
//        http
//                .cors().and()
//                .csrf().disable()
//                .authorizeRequests()
//                .antMatchers("/auth/**").permitAll() // 允许所有用户访问 /auth 下的端点
//                .antMatchers("/user/current").authenticated()
//                .antMatchers("/user/importData").permitAll()
//                .antMatchers("/totalWork/importTotalWork").permitAll()
//                .antMatchers("/researchProject/importData").permitAll()
//                .antMatchers("/academicWork/import").permitAll()
//                .antMatchers("/sumImportData/excel").permitAll()
////                .antMatchers("/user/register").permitAll() // 允许所有用户访问注册接口
////                .antMatchers("/profile/information").authenticated() // 只允许已认证用户访问个人信息
////                .antMatchers("/goods/goodsList").authenticated()
////                .antMatchers("/cart/cartList").authenticated()
////                .antMatchers("/cart//cartUserList").authenticated()
////                .antMatchers("/api/fileUpload").permitAll() // 允许所有用户访问文件上传接口
//                .anyRequest().authenticated() // 其他所有请求都需要认证
//                .and()
//                .logout()
//                .logoutUrl("/auth/logout")
//                .invalidateHttpSession(true)
//                .deleteCookies("JSESSIONID")
//                .and()
//                .formLogin()
//                .successHandler((httpServletRequest, httpServletResponse, authentication) -> {
//                    httpServletResponse.setStatus(HttpStatus.OK.value());
//                })
//                .failureHandler((httpServletRequest, httpServletResponse, exception) -> {
//                    httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
//                })
//         .and()
//                .exceptionHandling()
//                .authenticationEntryPoint((request, response, authException) -> {
//                    response.setContentType("application/json;charset=UTF-8");
//                    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
//                    response.getWriter().write("{\"error\":\"Unauthorized\",\"message\":\"用户未登录或认证失败\"}");
//                });
////                .logoutSuccessUrl("/auth/login");
//    }
//    @Bean
//    public PasswordEncoder passwordEncoder() {
//        return NoOpPasswordEncoder.getInstance();
//    }
////    @Bean
////    public PasswordEncoder passwordEncoder() {
////        return new BCryptPasswordEncoder();
////    }

}

